package shopping.web.servlet;

import shopping.domain.Category;
import shopping.exceptions.CategoryHasProductException;
import shopping.service.CategoryService;
import shopping.service.impl.CategoryServiceImpl;
import shopping.utils.BeanFactory;
import shopping.utils.UUIDUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/category")
public class CategoryServlet extends BaseServlet {
    private CategoryService categoryService = BeanFactory.newInstance(CategoryService.class);
    /**
     * 查询所有分类信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用Service查询数据
        List<Category> list =  new CategoryServiceImpl().findAll();
        //返回数据 json
        success(list);
    }

    /**
     * 添加分类
     */
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cname = request.getParameter("cname");
        if(cname == null || cname.trim().length() < 2 || cname.trim().length() > 6){
            fail("长度在2-6之间");
            return;
        }
        //封装对象
        Category category = new Category();
        category.setCid(UUIDUtil.getId());
        category.setCname(cname);

        categoryService.save(category);
        success();
    }

    /**
     * 查询分类名称
     */
    protected void findByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        Category category = categoryService.findById(cid);
        success(category);
    }

    /**
     * 更新分类名称
     */
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cname = request.getParameter("cname");
        if(cname == null || cname.trim().length() < 2 || cname.trim().length() > 6){
            fail("长度在2-6之间");
            return;
        }
        String cid = request.getParameter("cid");
        //封装对象
        Category category = new Category();
        category.setCid(cid);
        category.setCname(cname);

        categoryService.update(category);
        success();
    }

    /**
     * 删除分类
     */
    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取cid
        String cid = request.getParameter("cid");
        //调用service删除
        try {
            categoryService.del(cid);
            success();
        } catch (CategoryHasProductException e) {
            e.printStackTrace();
            fail("该分类下存在商品，无法删除");
        }
    }

}
